<template>
  <a-row id="globalHeader" align="center" :wrap="false">
    <a-col flex="auto">
      <div>
        <a-menu
          mode="horizontal"
          :selected-keys="selectedKeys"
          @menu-item-click="doMenuClick"
        >
          <a-menu-item
            key="0"
            :style="{ padding: 0, marginRight: '38px' }"
            disabled
          >
            <div class="title-bar">
              <img class="logo" src="../assets/oj-logo.svg" />
              <div class="title">一健 OJ</div>
            </div>
          </a-menu-item>
          <a-menu-item v-for="item in visibleRoutes" :key="item.path">
            {{ item.name }}
          </a-menu-item>
        </a-menu>
      </div>
    </a-col>
    <a-col flex="100px">
      <div @click="toLoginPage()">
        {{ store.state?.user?.loginUser?.userName ?? "未登录" }}
      </div>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { routes } from "@/router/routers";
import { useRouter } from "vue-router";
import { computed, ref } from "vue";
import { useStore } from "vuex";
import checkAccess from "@/access/CheckAccess";
import ACCESS_ENUM from "@/access/AccessEnum";

const router = useRouter();
// 全局状态
const store = useStore();
// 默认主页
const selectedKeys = ref(["/"]);

// 判断是否需要展示菜单
const visibleRoutes = computed(() => {
  return routes.filter((item, index) => {
    if (item.meta?.hideInMenu) {
      return false;
    }
    // 用户信息
    const loginUser = store.state.user.loginUser;
    // 根据权限过滤菜单
    if (!checkAccess(loginUser, item.meta?.access as string)) {
      return false;
    }
    return true;
  });
});

// 跳转至登录页面
const toLoginPage = () => {
  if (store.state.user.loginUser.userRole === ACCESS_ENUM.NOT_LOGIN) {
    router.push("/user/login");
  }
};

// const visibleRoutes = routes.filter((item, index) => {
//   if (item.meta?.hideInMenu) {
//     return false;
//   }
//   // 根据权限过滤菜单
//   if (!checkAccess(loginUser, item.meta?.access as string)) {
//     return false;
//   }
//   return true;
// });

// 路由跳转后，更新选中的菜单项
router.afterEach((to, from, failure) => {
  selectedKeys.value = [to.path];
});

setTimeout(() => {
  store.dispatch("user/getLoginUser", {
    userName: "一健管理员",
    userRole: ACCESS_ENUM.ADMIN,
  });
}, 1000);
const doMenuClick = (key: string) => {
  router.push({
    path: key,
  });
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: #444;
  margin-left: 16px;
}

.logo {
  height: 48px;
}
</style>
